package cn.it.config;

import cn.it.pojo.Configuration;
import cn.it.pojo.MappedStatement;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;

import java.io.InputStream;
import java.util.List;

public class XMLMapperBuilder {

    private Configuration configuration;

    public XMLMapperBuilder(Configuration configuration) {
        this.configuration = configuration;
    }

    public void parse(InputStream inputStream) throws DocumentException {

        Document document = new SAXReader().read(inputStream);
        Element rootElement = document.getRootElement();
        String namespace = rootElement.attributeValue("namespace");

        // 解析标签
        this.parseMappedStatement(rootElement.selectNodes("//select"),namespace);
        this.parseMappedStatement(rootElement.selectNodes("//insert"),namespace);
        this.parseMappedStatement(rootElement.selectNodes("//update"),namespace);
        this.parseMappedStatement(rootElement.selectNodes("//delete"),namespace);

    }

    private void parseMappedStatement(List<Element> list,String namespace){
        for (Element element : list) {
            String id = element.attributeValue("id");
            String paramterType = element.attributeValue("paramterType");
            String resultType = element.attributeValue("resultType");
            String sql = element.getTextTrim();
            configuration.getMap().put(namespace+"."+id,new MappedStatement(id, paramterType, resultType, sql));
        }
    }
}
